package com.baidu.user.service;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baidu.data.mapper.MongoDao;
import com.baidu.pojo.App;
import com.baidu.pojo.Cart;
import com.baidu.pojo.CartItem;
import com.baidu.pojo.Order;
import com.baidu.pojo.User;
import com.baidu.user.mapper.AppMapper;
import com.baidu.user.mapper.OrderMapper;

@Service
public class DataMongoService {

	@Autowired
	private MongoDao mongodao;
	@Autowired
	private AppMapper appMapper;
	@Autowired
	private OrderMapper orderMapper;

	public void getAppSku(String appsku, HttpServletRequest request) {
		App app = appMapper.selectByPrimaryKey(appsku);
		//创建购物车详单
		CartItem cartItem = new CartItem(System.currentTimeMillis() + "", app, 1);
		//判断用户是否登陆
		User user = (User) request.getSession().getAttribute("userinfo");
		Cart cart = null;
		if(user == null) {
			//若用户没有登陆通过IP获取购物车
			cart = mongodao.getCartById(request.getRemoteAddr());
			//若没有购物车则创建购物车
			if (cart == null) {
				cart = new Cart();
				cart.setId(request.getRemoteAddr());
			}    	
		} else {
			//若用户登陆则通过用户ID获取购物车
			cart = mongodao.getCartById(user.getId());
			//若用户没有购物车则创建购物车
			if(cart == null) {
				cart = new Cart();
				cart.setId(user.getId());
			}
		}
		cart.add(cartItem);
		mongodao.saveCart(cart);
	}

	public Cart getCartList(HttpServletRequest request) {
		//判断用户是否登陆
		User user = (User) request.getSession().getAttribute("userinfo");
		Cart cart=null;
		if(user == null) {
			cart=mongodao.getCartList(request.getRemoteAddr());
		}else{
			cart=mongodao.getCartList(user.getId());
		}
		return cart;
	}

	public void doAddApp(HttpServletRequest request) {
		//根据前台传过来的ID从mongo中
	
		User user = (User) request.getSession().getAttribute("userinfo");
		Cart cart=null;
		String id=null;
		if(user == null) {
			id=request.getRemoteAddr();
			cart=mongodao.getCartList(id);
		}else{
			id=user.getId();
			cart=mongodao.getCartList(id);
		}
		List<CartItem> list = cart.getItems();
		
		for (CartItem cartItem : list) {
			Order order = new Order(System.currentTimeMillis()+"",id,null,cartItem.getBuyNum()*Integer.parseInt(cartItem.getApp().getPrice())+"",null,0);
			orderMapper.insertSelective(order);
		}
		
	
	}

	public void dodelApp(String id) {
		mongodao.del(id);
	}






}
